package logic

import (
	"time"
	"web_app/dao/mysql"
	"web_app/models"
	"web_app/pkg/jwt"
	"web_app/pkg/snowflake"

	"github.com/jinzhu/gorm"
)

func Register(p *models.ParamUserRegister) (err error) {
	err = mysql.CheckUserExistByUsername(p.Username)
	//如果err 不为nil  且 不是 查询不到数据 才返回err
	if err != nil && !gorm.IsRecordNotFoundError(err) {
		return err
	}

	//1.生成uid
	userId, err := snowflake.GetID()
	//构造一个User实例
	t := time.Now()

	user := &models.User{
		UserId:    userId,
		Username:  p.Username,
		Password:  p.Password,
		CreatedAt: t,
		UpdatedAt: t,
	}
	//2.存入数据库
	return mysql.InsertUser(user)
}

//func Select() {
//	mysql.SelectUser()
//}

func Login(p *models.ParamUserLogin) (user *models.User, err error) {
	user = &models.User{
		Username: p.Username,
		Password: p.Password,
	}
	//参数为指针
	err = mysql.CheckUserExist(user)
	if err != nil {
		return nil, err
	}
	//生成JWT
	token, err := jwt.GetToken(user.UserId, user.Username)
	if err != nil {
		return
	}
	user.Token = token
	return

}
